﻿using Flurl.Http;
using Jupiter.Infrastructure.Exceptions;
using Jupiter.Infrastructure.Responses;
using Newtonsoft.Json;
using Wips.Infrastructure.Helpers;
using Wips.Infrastructure.Interfaces;
using Wips.Infrastructure.Options;

namespace Wips.Infrastructure.Realizes
{

    /// <summary>
    /// 发布子服务实现
    /// </summary>
    public class PublishAgentService : IPublishAgentService
    {

        /// <summary>
        /// 配置
        /// </summary>
        private readonly AgentServerOption options;
        private readonly AuthConfig authConfig;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="options"></param>
        public PublishAgentService(IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            options = configuration.GetSection("ServerOptions").Get<AgentServerOption>()!;
            authConfig = configuration.GetSection("AuthConfig").Get<AuthConfig>()!;
        }

        /// <summary>
        /// 启动
        /// </summary>
        public async Task<bool> RunAsync()
        {
            // 执行注册任务
            var result = await
                (options.MasterAddress + Consts.MapRegisterAgentServerPath)
                .WithHeader("sign", Rsa2Helper.SignDataWithPrivateKey(Consts.MapRegisterAgentServerPath + JsonConvert.SerializeObject(new
                {
                    ServerName = options.ServerName,
                    ServerKey = options.ServerKey,
                    AgentAddress = options.AgentAddress
                }), authConfig.PrivateKey))
                .PostJsonAsync(new
                {
                    ServerName = options.ServerName,
                    ServerKey = options.ServerKey,
                    AgentAddress = options.AgentAddress
                })
                .ReceiveJson<ApiResult<string>>();

            if (!result.Success)
            {
                throw new CoreException($"注册子服务报错：{result.Message}");
            }

            return true;
        }
    }
}
